﻿using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using com.ContrivedExample.SQLTools;

namespace com.ContrivedExample
{
    public partial class SqlSpyForm : Form
    {
        com.ContrivedExample.SQLTools.Tracer theTracer;
        private bool TraceRunning;
        BindingList<TraceData> tdList = new BindingList<TraceData>();

        public SqlSpyForm()
        {
            InitializeComponent();
            this.Icon = Properties.Resources.sql;
        }

        private void SqlSpyForm_Load(object sender, EventArgs e)
        {
            TraceDGV.AutoGenerateColumns = true;            
        }

        private void SettingsToggleBtn_Click(object sender, EventArgs e)
        {
            splitContainer1.Panel1Collapsed = splitContainer1.Panel1Collapsed ? false : true;
        }

        private void StartBtn_Click(object sender, EventArgs e)
        {
            if (ValidateInput())
            {
                try
                {
                    theTracer = new Tracer(ServerTB.Text);
                    theTracer.UsesIntegratedSecurity = IntSecCheckBox.Checked;
                    theTracer.UserName = UserNameTB.Text;
                    theTracer.Password = PasswordTextBox.Text;

                    if (FilterOnUsernameCB.Checked)
                    {
                        theTracer.UsesNTUserName = true;
                        theTracer.NTUserName = NtUsernameTB.Text;
                    }
                    else
                    {
                        theTracer.UsesNTUserName = false;
                    }

                    theTracer.UsesBatch = ShowBatchCB.Checked;

                    theTracer.TraceUpdated += new TraceEventHandler(theTracer_TraceUpdated);
                    theTracer.BackgroundError += theTracer_BackgroundError;
                    theTracer.Start();

                    TraceRunning = true;
                    RunningStatusLabel.Text = "Trace Is running";
                    RunningStatusLabel.ForeColor = Color.Green;

                    traceBindingSrc.DataSource = tdList;

                    TraceDGV.Columns[1].MinimumWidth = 100;
                    TraceDGV.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                    ConfigureColumns();

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        void theTracer_TraceUpdated(object sender, SQLTools.TraceEventArgs e)
        {
            TraceData td = e.EventTraceData;
            tdList.Add(td);
            if (TraceDGV.RowCount > 0)
                TraceDGV.FirstDisplayedScrollingRowIndex = TraceDGV.RowCount - 1;
        }


        void theTracer_BackgroundError(object sender, EventArgs e)
        {
            TraceRunning = false;
            RunningStatusLabel.Text = "Trace is Not running";
            RunningStatusLabel.ForeColor = Color.Black;

            RunWorkerCompletedEventArgs eARgs = e as RunWorkerCompletedEventArgs;
            string errmsg = eARgs.Error.Message;

            Exception ex = eARgs.Error.InnerException;

            while (ex != null)
            {
                errmsg += "\n" + ex.Message;
                ex = ex.InnerException;
            }

            MessageBox.Show(errmsg);
        }

        private bool ValidateInput()
        {
            bool isvalid = true;

            if (string.IsNullOrWhiteSpace(ServerTB.Text))
            {
                errProv.SetError(ServerTB, "Server Name is required.");
                isvalid = false;
            }
            else
            {
                errProv.SetError(ServerTB, "");
            }

            if (!IntSecCheckBox.Checked)
            {
                if (string.IsNullOrWhiteSpace(UserNameTB.Text) || string.IsNullOrWhiteSpace(PasswordTextBox.Text))
                {
                    errProv.SetError(IntSecCheckBox, "User name and password are required for SQL authentication");
                    isvalid = false;
                }
                else
                {
                    errProv.SetError(IntSecCheckBox, "");
                }
            }
            else
            {
                errProv.SetError(IntSecCheckBox, "");
            }

            if (FilterOnUsernameCB.Checked)
            {
                if (string.IsNullOrWhiteSpace(NtUsernameTB.Text))
                {
                    errProv.SetError(NtUsernameTB, "NT Username required when checked");
                    isvalid = false;
                }
                else
                {
                    errProv.SetError(NtUsernameTB, "");
                }
            }

            return isvalid;
        }

        private void SaveSettings()
        {
            Properties.Settings.Default.Save();
        }

        private void StopBtn_Click(object sender, EventArgs e)
        {
            if (theTracer != null)
            {
                theTracer.Stop();
                RunningStatusLabel.Text = "Trace is Not running";
                RunningStatusLabel.ForeColor = Color.Black;
            }
        }

        private void SqlSpyForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (theTracer != null)
            {
                theTracer.Stop();
                RunningStatusLabel.Text = "Trace is Not running";
                RunningStatusLabel.ForeColor = Color.Black;
            }

            SaveSettings();
        }

        private void ClearBtn_Click(object sender, EventArgs e)
        {
            traceBindingSrc.Clear();
        }

        private void TraceDGV_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //Show the contents of the cell in the text box
            if (e.RowIndex > 0 && e.ColumnIndex >= 0)
                 OutputRTB.Text = TraceDGV[e.ColumnIndex, e.RowIndex].Value.ToString();
        }

        private void IntSecCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            UserNameTB.Enabled = PasswordTextBox.Enabled = !IntSecCheckBox.Checked;
        }

        private void ConfigureColumns()
        {
            if (TraceDGV.Columns.Count > 0)
            {
                TraceDGV.Columns[0].Visible = EventClassCB.Checked;
                TraceDGV.Columns[2].Visible = ApplicationNameCB.Checked;
                TraceDGV.Columns[3].Visible = NTUsernameCB.Checked;
                TraceDGV.Columns[4].Visible = LoginNameCB.Checked;
                TraceDGV.Columns[5].Visible = CpuCB.Checked;
                TraceDGV.Columns[6].Visible = ReadsCB.Checked;
                TraceDGV.Columns[7].Visible = WritesCB.Checked;
                TraceDGV.Columns[8].Visible = DurationCB.Checked;
                TraceDGV.Columns[9].Visible = ClientProcessIdCB.Checked;
                TraceDGV.Columns[10].Visible = SpidCB.Checked;
                TraceDGV.Columns[11].Visible = StartTimeCB.Checked;
                TraceDGV.Columns[12].Visible = EndTimeCB.Checked;
            }
        }

        private void CheckedChanged(object sender, EventArgs e)
        {
            ConfigureColumns();
        }
    }
}
